package org.jeecg.common.util;

import cn.hutool.core.util.StrUtil;
import org.jeecg.common.util.util_entity.ContentTypeEnum;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

/**
 * @author zjarlin
 * @since 2023/11/28 10:25
 */
@Component
public class DownloadUtil {

    @Autowired
    public  void setHttpServletRequest(HttpServletRequest httpServletRequest) {
        DownloadUtil.httpServletRequest = httpServletRequest;
    }

    private static HttpServletRequest httpServletRequest;

    @Autowired
    public  void setHttpServerResponse(HttpServletResponse httpServerResponse) {
        DownloadUtil.httpServerResponse = httpServerResponse;
    }

    private static HttpServletResponse httpServerResponse;


    /**
     * 调用浏览器文件下载
     */
    @SneakyThrows
    public static void downloadExcel(String fileName, Consumer<OutputStream> consumer) {
        download(fileName, consumer, ContentTypeEnum.XLSX);
    }

    @SneakyThrows
    public static void download(String fileName, Consumer<OutputStream> consumer, ContentTypeEnum tab) {
        String application = tab.getApplication();
        String postfix = tab.getPostfix();
        httpServerResponse.setCharacterEncoding("UTF-8");
        //得请求头中的User-Agent
        String agent = httpServletRequest.getHeader("User-Agent");

        // 根据不同的客户端进行不同的编码
        String filenameEncoder = "";
        if (agent.contains("MSIE")) {
            // IE浏览器
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
            filenameEncoder = filenameEncoder.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filenameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes(StandardCharsets.UTF_8)) + "?=";
        } else {
            // 其它浏览器
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
        }

        filenameEncoder = StrUtil.addSuffixIfNot(filenameEncoder, postfix);
//        filenameEncoder = URLDecoder.decode(fileName, StandardCharsets.UTF_8);
        httpServerResponse.setHeader("Content-disposition", "attachment;filename=" + filenameEncoder);
        httpServerResponse.setContentType(application);
        OutputStream outputStream = httpServerResponse.getOutputStream();
        consumer.accept(outputStream);
    }

}
